
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Route," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>路由定义 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        路由定义
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Route/" rel="tag">Ember-Route</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 5 分钟</span>
    </header>

    <div class="post-content">
      <p>当你的应用启动的时候，路由器就会匹配当前的URL到你定义的路由上。然后按照定义的路由层次逐个加载数据、设置应用程序状态、渲染路由对应的模板。</p>
<h3 id="1，基本路由"><a href="#1，基本路由" class="headerlink" title="1，基本路由"></a>1，基本路由</h3><p>在<code>app/router.js</code>的<code>map</code>方法里定义的路由会映射到当前的URL。当<code>map</code>方法被调用的时候方法体内的<code>route</code>方法就会创建路由。</p>
<p>下面使用<a target="_blank" rel="noopener" href="http://ember-cli.com/user-guide">Ember CLI</a>命令创建两个路由：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ember generate route about</span><br><span class="line">ember generate route favorites</span><br></pre></td></tr></table></figure>
<p>命令执行完之后你可在你的项目目录<code>app/routes</code>下面看到已经创建好的两个路由文件已经<code>app/templates</code>下面路由对应的模板文件。<br>此时在<code>app/router.js</code>的<code>map</code>方法中已经存在了刚刚创建的路由配置。这个是<a target="_blank" rel="noopener" href="http://ember-cli.com/user-guide">Ember CLI</a>自动为你创建了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/router.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> config <span class="keyword">from</span> <span class="string">&#x27;./config/environment&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> Router = Ember.Router.extend(&#123;</span><br><span class="line">  location: config.locationType</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">Router.map(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.route(<span class="string">&#x27;about&#x27;</span>);</span><br><span class="line">  <span class="built_in">this</span>.route(<span class="string">&#x27;favorites&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Router;</span><br></pre></td></tr></table></figure>
<p>现在分别修改<code>app/templates</code>下面的两个模板文件如下：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/about.hbs --&gt;</span></span><br><span class="line"></span><br><span class="line">这个是about模板！<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">&#123;&#123;outlet&#125;&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/favorites.hbs --&gt;</span></span><br><span class="line"></span><br><span class="line">这个是favorites模板！<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">&#123;&#123;outlet&#125;&#125;</span><br></pre></td></tr></table></figure>

<p>然后访问<a target="_blank" rel="noopener" href="http://localhost:4200/about">http://localhost:4200/about</a>或者<a target="_blank" rel="noopener" href="http://localhost:4200/favorites">http://localhost:4200/favorites</a>，如果你的程序没有问题你也会得到如下显示结果：</p>
<p><img src="/content/images/2016/03/55.png" alt="run result"></p>
<p>如果你觉得<code>favorites</code>这个路由名字太长是否可以修改成其他名字呢？答案是肯定的，你只要修改<code>router.js</code>中<code>map</code>方法的配置即可。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Router.map(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.route(<span class="string">&#x27;about&#x27;</span>);</span><br><span class="line">  <span class="comment">// 注意：访问的URL可以写favs但是项目中如果是使用route的地方仍然是使用favorites</span></span><br><span class="line">  <span class="built_in">this</span>.route(<span class="string">&#x27;favorites&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/favs&#x27;</span> &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>此时访问：<a target="_blank" rel="noopener" href="http://localhost:4200/favs">http://localhost:4200/favs</a>，界面显示的结果与之前是一样的。</p>
<p><strong>说明</strong>：默认情况下访问的URL与路由名字是一致的，比如<code>this.route(&#39;about&#39;)</code>与<code>this.route('about', { path: ‘/about’ })</code>是同一个路由，如果URL与路由不同名则需要使用<code>{path: '/xxx'}</code>设置映射的URL。</p>
<p>在handlebars模板中可以使用<code>{{link-to}}</code>助手在不同的路由间切换，使用时需要在<code>link-to</code>助手内指定路由名称。比如下面的代码使用<code>link-to</code>助手实现在<code>about</code>和<code>favs</code>两个路由间切换。<br>为了页面能美观一点引入<a target="_blank" rel="noopener" href="http://www.bootcss.com/">bootstrap</a>，使用<a target="_blank" rel="noopener" href="https://www.npmjs.com/">npm</a>命令安装：<code>bower install bootstrap</code>，如果安装成功你可以在bower_components目录下看到<a target="_blank" rel="noopener" href="http://www.bootcss.com/">bootstrap</a>相关的文件。安装成功之后引入到项目中，修改<code>chapter3_routes/ember-cli-build.js</code>。在<code>return</code>语句前加入如下两行代码(作用就是引入<a target="_blank" rel="noopener" href="http://www.bootcss.com/">bootstrap</a>框架)：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">app.import(<span class="string">&quot;bower_components/bootstrap/dist/css/bootstrap.css&quot;</span>);</span><br><span class="line">app.import(<span class="string">&quot;bower_components/bootstrap/dist/js/bootstrap.js&quot;</span>);</span><br></pre></td></tr></table></figure>
<p>修改<code>application.hbs</code>，增加一个导航菜单。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- //app/templates/application.hbs --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">nav</span> <span class="attr">class</span>=<span class="string">&quot;navbar navbar-inverse navbar-fixed-top&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;container-fluid&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;navbar-header&quot;</span> <span class="attr">href</span>=<span class="string">&quot;#&quot;</span>&gt;</span></span><br><span class="line">                <span class="comment">&lt;!--  &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;Blog&lt;/a&gt; --&gt;</span></span><br><span class="line">                &#123;&#123;#link-to &#x27;index&#x27; class=&quot;navbar-brand&quot;&#125;&#125;Home&#123;&#123;/link-to&#125;&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;nav navbar-nav&quot;</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">li</span>&gt;</span>&#123;&#123;#link-to &#x27;about&#x27;&#125;&#125;about&#123;&#123;/link-to&#125;&#125;<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">li</span>&gt;</span>&#123;&#123;#link-to &#x27;favorites&#x27;&#125;&#125;favorites&#123;&#123;/link-to&#125;&#125;<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;nav navbar-nav navbar-right&quot;</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">li</span>&gt;</span><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">&quot;#&quot;</span>&gt;</span>Login<span class="tag">&lt;/<span class="name">a</span>&gt;</span><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">li</span>&gt;</span><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">&quot;#&quot;</span>&gt;</span>Logout<span class="tag">&lt;/<span class="name">a</span>&gt;</span><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">nav</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;container-fluid&quot;</span> <span class="attr">style</span>=<span class="string">&quot;margin-top: 70px;&quot;</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 项目中其他所有的模板都是application的子模板，所以其他模板都会渲染到这里的 outlet上 --&gt;</span></span><br><span class="line">&#123;&#123;outlet&#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>如果看到页面没有<a target="_blank" rel="noopener" href="http://www.bootcss.com/">bootstrap</a>效果请重新启动项目。如果运行项目后再浏览器控制台出现如下错误。</p>
<p><img src="/content/images/2016/03/56.png" alt="run result"></p>
<p>如果出现上图错误需要在<code>config/environment.js</code>中加上一些安全策略设置代码，有关设置的解释请看下面网址的文章介绍。</p>
<ol>
<li><a target="_blank" rel="noopener" href="https://blog.justinbull.ca/ember-cli-and-content-security-policy-csp/">ember-cli-and-content-security-policy-cs</a></li>
<li><a target="_blank" rel="noopener" href="https://www.w3.org/TR/2015/CR-CSP2-20150721/">https://www.w3.org/TR/2015/CR-CSP2-20150721/</a></li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">, <span class="attr">contentSecurityPolicy</span>: &#123;</span><br><span class="line">      <span class="string">&#x27;default-src&#x27;</span>: <span class="string">&quot;&#x27;none&#x27;&quot;</span>,</span><br><span class="line">      <span class="string">&#x27;script-src&#x27;</span>: <span class="string">&quot;&#x27;self&#x27; &#x27;unsafe-inline&#x27; &#x27;unsafe-eval&#x27; use.typekit.net connect.facebook.net maps.googleapis.com maps.gstatic.com&quot;</span>,</span><br><span class="line">      <span class="string">&#x27;font-src&#x27;</span>: <span class="string">&quot;&#x27;self&#x27; data: use.typekit.net&quot;</span>,</span><br><span class="line">      <span class="string">&#x27;connect-src&#x27;</span>: <span class="string">&quot;&#x27;self&#x27;&quot;</span>,</span><br><span class="line">      <span class="string">&#x27;img-src&#x27;</span>: <span class="string">&quot;&#x27;self&#x27; www.facebook.com p.typekit.net&quot;</span>,</span><br><span class="line">      <span class="string">&#x27;style-src&#x27;</span>: <span class="string">&quot;&#x27;self&#x27; &#x27;unsafe-inline&#x27; use.typekit.net&quot;</span>,</span><br><span class="line">      <span class="string">&#x27;frame-src&#x27;</span>: <span class="string">&quot;s-static.ak.facebook.com static.ak.facebook.com www.facebook.com&quot;</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p><img src="/content/images/2016/03/57.png" alt="配置截图"></p>
<p>上图是我的演示项目配置。然后点击<code>about</code>会得到如下界面</p>
<p><img src="/content/images/2016/03/58.png" alt="result"></p>
<p>可以看到浏览器地址栏的URL变为<code>about</code>了，并且页面显示的内容也是<code>about</code>模板的内容。同理你点击<code>favorites</code>地址栏就变为<a target="_blank" rel="noopener" href="http://localhost:4200/favs">http://localhost:4200/favs</a>并且显示的内容是<code>favorites</code>的（为什么URL是<code>favs</code>而不是<code>favorites</code>呢，因为前面已经修改了<code>route</code>和URL的映射关系，路由<code>favorites</code>对应的URL是<code>favs</code>）。<br>上述演示的就是路由的切换！！！</p>
<p>可以看到浏览器地址栏的URL变为about了，并且页面显示的内容也是about模板的内容。同理你点击“favorites”地址栏就变为<a target="_blank" rel="noopener" href="http://localhost:4200/favs%E5%B9%B6%E4%B8%94%E6%98%BE%E7%A4%BA%E7%9A%84%E5%86%85%E5%AE%B9%E6%98%AFfavorites%E7%9A%84%EF%BC%88%E4%B8%BA%E4%BB%80%E4%B9%88URL%E6%98%AFfavs%E8%80%8C%E4%B8%8D%E6%98%AFfavorites%E5%91%A2%EF%BC%8C%E5%9B%A0%E4%B8%BA%E5%89%8D%E9%9D%A2%E5%B7%B2%E7%BB%8F%E4%BF%AE%E6%94%B9%E4%BA%86route%E5%92%8CURL%E7%9A%84%E6%98%A0%E5%B0%84%E5%85%B3%E7%B3%BB%EF%BC%8C%E8%B7%AF%E7%94%B1favorites%E5%AF%B9%E5%BA%94%E7%9A%84URL%E6%98%AFfavs%EF%BC%89%E3%80%82">http://localhost:4200/favs并且显示的内容是favorites的（为什么URL是favs而不是favorites呢，因为前面已经修改了route和URL的映射关系，路由favorites对应的URL是favs）。</a><br>上述演示的就是路由的切换！！！</p>
<h3 id="2，路由嵌套"><a href="#2，路由嵌套" class="headerlink" title="2，路由嵌套"></a>2，路由嵌套</h3><p>还记得在前面的<a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/03/22/ember-js-ru-men-zhi-nan-zhi-shi-san-link-to/">Ember.js 入门指南之十三{{link-to}} 助手</a>这篇文章的内容吗？在这篇文章中比较详细的介绍了路由的嵌套与怎么使用嵌套的路由。不妨回过头去看看。在这里打算就不讲了⋯⋯如果有不明白的请看官网的教程。</p>
<h3 id="3，application路由"><a href="#3，application路由" class="headerlink" title="3，application路由"></a>3，application路由</h3><p><code>application</code>路由是默认的路由，是程序的入口，所有其他自定义的路由都先进过<code>application</code>才到自定义的路由。并且<code>application</code>路由对应的<code>application.hbs</code>模板是所有自定义模板的父模板，所有自定义的模板都会渲染到application.hbs模板的<code>{{outlet}}</code>上。有关于路由的执行顺序以及模板的渲染顺序在前面的<a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/03/22/ember-js-ru-men-zhi-nan-zhi-shi-san-link-to/">Ember.js 入门指南之十三{{link-to}} 助手</a>也讲过了，在此也不打算在做过多的介绍了。你可以回头看之前的文章或者到官网查看。</p>
<h3 id="4，index路由"><a href="#4，index路由" class="headerlink" title="4，index路由"></a>4，index路由</h3><p>对于所有的嵌套的路由，包括最顶层的路由Ember会自动生成一个访问URL为<code>/</code>对应路由名称为<code>index</code>的路由。</p>
<p>比如下面的两种路由设置是等价的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/router.js</span></span><br><span class="line"><span class="comment">// ⋯⋯</span></span><br><span class="line"></span><br><span class="line">Router.map(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;about&#x27;</span>);</span><br><span class="line">    <span class="comment">// 注意：访问的URL可以写favs但是项目中如果是使用route的地方仍然是使用favorites</span></span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;favorites&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/favs&#x27;</span> &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Router;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/router.js</span></span><br><span class="line"><span class="comment">// ⋯⋯</span></span><br><span class="line"></span><br><span class="line">Router.map(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.route(<span class="string">&#x27;index&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/&#x27;</span> &#125;);</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;about&#x27;</span>);</span><br><span class="line">    <span class="comment">// 注意：访问的URL可以写favs但是项目中如果是使用route的地方仍然是使用favorites</span></span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;favorites&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/favs&#x27;</span> &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Router;</span><br></pre></td></tr></table></figure>
<p><code>index</code>路由会渲染到<code>application.hbs</code>模板的<code>{{outlet}}</code>上。这个是Ember默认设置。当用户访问<code>/about</code>时Ember会把<code>index</code>模板替换为<code>about</code>模板。</p>
<p>对于路由嵌套的情况也是如此。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/router.js</span></span><br><span class="line"><span class="comment">//  ⋯⋯</span></span><br><span class="line">Router.map(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;posts&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="built_in">this</span>.route(<span class="string">&#x27;new&#x27;</span>);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Router;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/router.js</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  ⋯⋯</span></span><br><span class="line">Router.map(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.route(<span class="string">&#x27;index&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/&#x27;</span> &#125;);</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;posts&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="built_in">this</span>.route(<span class="string">&#x27;index&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/&#x27;</span> &#125;);</span><br><span class="line">      <span class="built_in">this</span>.route(<span class="string">&#x27;new&#x27;</span>);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Router;</span><br></pre></td></tr></table></figure>
<p>两种设置方式都会得到如下图的路由表。打开浏览器的“开发者工具”点开“Ember”选项卡，在点开“/#Routes”你就可以看到如下路由表（显示是顺序有可能跟你的不一样）。</p>
<p><img src="/content/images/2016/03/59.png" alt="路由渲染结果"></p>
<p>注：<code>loading</code>和<code>error</code>这两个路由是ember自动生成的，他们的用法会在后面的文章介绍。</p>
<p>当用户访问<code>/posts</code>时实际进入的路由是<code>posts.index</code>对应的模板是<code>posts/index.hbs</code>，但是实际中我并没有创建这个模板，因为Ember默认把这个模板渲染到<code>posts.hbs</code>的<code>{{outlet}}</code>上。由于这个模板不存在也就相当于什么都没做。当然你也可以创建这个模板。<br><br>使用命令：<code>ember generate template posts/index</code>然后在这个模板中添加以下显示的内容：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/posts/index.hbs  --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">h2</span>&gt;</span>这里是/posts/index.hbs。。。<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>再此访问<a target="_blank" rel="noopener" href="http://localhost:4200/posts">http://localhost:4200/posts</a>，是不是可以看到增加的内容了。</p>
<p>你可以这么理解对于每一个有子路由的路由都有一个名为<code>index</code>的子路由并且这个路由对应的模板为<code>index.hbs</code>，如果把有子路由的路由当做一个模块看待那么<code>index.hbs</code>就是这个模块的首页。特别是做过一些信息系统的朋友应该是很熟悉的，基本上没个子模块都会有一个首页，这个首页现实的内容就是一进入这个模块时就显示的内容。既然是子模板当然也不会例外它也会渲染到父模板的<code>{{outlet}}</code>上。比如上面的例子当用户访问<a target="_blank" rel="noopener" href="http://localhost:4200/posts">http://localhost:4200/posts</a>实际进入的是<a target="_blank" rel="noopener" href="http://localhost:4200/posts/">http://localhost:4200/posts/</a>（后面多了一个<code>/</code>，这个<code>/</code>对应的模板就是<code>index</code>），当用户访问的是<a target="_blank" rel="noopener" href="http://localhost:4200/posts/new">http://localhost:4200/posts/new</a>，那么进入的就是<code>posts/new.hbs</code>这个模板（也是渲染到<code>posts.hbs</code>的<code>{{outlet}}</code>上）。</p>
<h3 id="4，动态段"><a href="#4，动态段" class="headerlink" title="4，动态段"></a>4，动态段</h3><p>关于动态段在前面的<a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/03/22/ember-js-ru-men-zhi-nan-zhi-shi-san-link-to/">Ember.js 入门指南之十三{{link-to}} 助手</a>也介绍过了，在这里就再简单补充下。</p>
<p>路由最主要的任务之一就是加载<code>model</code>。</p>
<p>例如对于路由<code>this.route(&#39;posts&#39;);</code>会加载项目中所有的<code>posts</code>下的<code>model</code>。但是当你只想加载其中一个<code>model</code>的时候怎么处理呢？而且大多数情况我们是不需要一次性加载完全部数据的，一般情况都是加载其中一小部分。这个时候就需要动态段了！</p>
<p>动态段以<code>:</code>开头，并且后面接着<code>model</code>的<code>id</code>属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/router.js</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  ⋯⋯</span></span><br><span class="line"></span><br><span class="line">Router.map(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;about&#x27;</span>);</span><br><span class="line">    <span class="comment">// 注意：访问的URL可以写favs但是项目中如果是使用route的地方仍然是使用favorites</span></span><br><span class="line">    <span class="comment">// this.route(&#x27;favorites&#x27;, &#123; path: &#x27;/favs&#x27; &#125;);</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;posts&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="built_in">this</span>.route(<span class="string">&#x27;post&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/:post_id&#x27;</span>&#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">    </span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Router;</span><br></pre></td></tr></table></figure>
<p>此时你可以访问<a target="_blank" rel="noopener" href="http://localhost:4200/posts/1">http://localhost:4200/posts/1</a>，不过我们还没创建<code>model</code>所以会报错。这个我们暂时不管，后面会有一章是介绍<code>model</code>的。现在只要知道你访问<a target="_blank" rel="noopener" href="http://localhost:4200/posts/1">http://localhost:4200/posts/1</a>就相当于获取<code>id</code>值唯一的<code>model</code>。</p>
<h3 id="5，通配符-全局路由"><a href="#5，通配符-全局路由" class="headerlink" title="5，通配符/全局路由"></a>5，通配符/全局路由</h3><p>Ember也同样运行你使用<code>*</code>作为URL通配符。有了通配符你可以设置多个URL访问同一个路由。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">this</span>.route(<span class="string">&#x27;about&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/*wildcard&#x27;</span> &#125;);</span><br></pre></td></tr></table></figure>
<p>然后访问：<a target="_blank" rel="noopener" href="http://localhost:4200/wildcard">http://localhost:4200/wildcard</a>或者访问<a target="_blank" rel="noopener" href="http://localhost:4200/2423432ffasdfewildcard">http://localhost:4200/2423432ffasdfewildcard</a>或者<a target="_blank" rel="noopener" href="http://localhost:4200/2333">http://localhost:4200/2333</a>都是可以进入到<code>about</code>这个路由，但是<a target="_blank" rel="noopener" href="http://localhost:4200/posts">http://localhost:4200/posts</a>仍然进入的是<code>posts</code>这个路由。因为可以匹配到这个路由。</p>
<h3 id="6，重置子路由的命名空间"><a href="#6，重置子路由的命名空间" class="headerlink" title="6，重置子路由的命名空间"></a>6，重置子路由的命名空间</h3><p>在有路由嵌套的情况下，一般情况我们访问URL的格式都是<code>父路由名/子路由名</code>，Ember提供了一个<code>resetNamespace:true</code>选项可以用户重置子路由的命名空间，使用这个设置的路由可以直接这样访问<code>/子路由名</code>，不需要写父路由名。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">this</span>.route(<span class="string">&#x27;posts&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;post&#x27;</span>, &#123; <span class="attr">path</span>: <span class="string">&#x27;/:post_id&#x27;</span>&#125;);</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;comments&#x27;</span>, &#123; <span class="attr">resetNamespace</span>: <span class="literal">true</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="built_in">this</span>.route(<span class="string">&#x27;new&#x27;</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>此时如果你想问的<code>new</code>这个路由你可以直接不写<code>comments</code>。<a target="_blank" rel="noopener" href="http://localhost:4200/posts/new">http://localhost:4200/posts/new</a>，而不需要<a target="_blank" rel="noopener" href="http://localhost:4200/posts/comments/new">http://localhost:4200/posts/comments/new</a>，不过模板渲染的顺序没变，<code>new</code>模板仍然是渲染到<code>comments</code>的<code>{{outlet}}</code>上。</p>
<p>不过个人觉得还是不使用这个设置比较好，特别是在开发的时候你可以看到访问的URL的层次，对你调试代码还是很有帮助的。</p>
<p>以上的内容就是定义路由的全部内容。都是非常重要的知识，希望你能好好掌握，对于路由的嵌套请看之前的文章。如果有疑问请给我留言或者访问官网看原教程。<br><br><br>博文完整代码放在<a target="_blank" rel="noopener" href="https://github.com/ubuntuvim/my_emberjs_code">Github</a>（博文经过多次修改，博文上的代码与github代码可能又出入，不过影响不大！），如果你觉得博文对你有点用，请在github项目上给我点个<code>star</code>吧。您的肯定对我来说是最大的动力！！</p>

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/routing/%E8%B7%AF%E7%94%B1%E9%87%8D%E5%AE%9A%E5%90%91/" rel="next" title="路由重定向">
          路由重定向
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/routing/%E7%BB%88%E6%AD%A2%E4%B8%8E%E9%87%8D%E8%AF%95%E8%B7%AF%E7%94%B1%E8%B7%B3%E8%BD%AC/" rel="prev" title="终止与重试路由跳转">
            终止与重试路由跳转
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%EF%BC%8C%E5%9F%BA%E6%9C%AC%E8%B7%AF%E7%94%B1"><span class="toc-text">1，基本路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%EF%BC%8C%E8%B7%AF%E7%94%B1%E5%B5%8C%E5%A5%97"><span class="toc-text">2，路由嵌套</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%EF%BC%8Capplication%E8%B7%AF%E7%94%B1"><span class="toc-text">3，application路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%EF%BC%8Cindex%E8%B7%AF%E7%94%B1"><span class="toc-text">4，index路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%EF%BC%8C%E5%8A%A8%E6%80%81%E6%AE%B5"><span class="toc-text">4，动态段</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%EF%BC%8C%E9%80%9A%E9%85%8D%E7%AC%A6-%E5%85%A8%E5%B1%80%E8%B7%AF%E7%94%B1"><span class="toc-text">5，通配符&#x2F;全局路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6%EF%BC%8C%E9%87%8D%E7%BD%AE%E5%AD%90%E8%B7%AF%E7%94%B1%E7%9A%84%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4"><span class="toc-text">6，重置子路由的命名空间</span></a></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '路由定义', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
